package com.wdhcr.service.imp;

import com.wdhcr.entity.Type;
import com.wdhcr.repository.TypeRepository;
import com.wdhcr.service.TypeService;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    TypeRepository typeRepository;



    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeRepository.findTop(pageable);
    }


    @Override
    public Type saveType(Type type) {

        return typeRepository.save(type);
    }

    @Override
    public Type getType(Long id) {
//        springboot 2.x 版本后，较之前的版本在此方法的使用上有差:
//        如果找到匹配的id数据，则赋值给foo;否则则将括号中的对象赋值给foo。
        return typeRepository.findById(id).get();

    }

    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    @Override
//    分页查询
    public Page<Type> listType(Pageable pageable) {

        return typeRepository.findAll(pageable);
    }

    @Override
    public Type updateType(Long id, Type type) throws NotFoundException {
        Type type1 = typeRepository.getOne(id);
        if (type1 == null){
            throw new NotFoundException("你所查询的分类类型不存在");
        }
//        将type复制到type1中
        BeanUtils.copyProperties(type,type1);
//        更新
        return typeRepository.save(type1);
    }

    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);

    }
}


